import 'package:bilibili/page/favorite_page.dart';
import 'package:bilibili/page/home_page.dart';
import 'package:bilibili/page/profile_page.dart';
import 'package:bilibili/page/ranking_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/util/color.dart';
import 'package:hi_common/util/logger.dart';


class BottomNavigator extends StatefulWidget {
  const BottomNavigator({super.key});

  @override
  State<StatefulWidget> createState() {
    return _bottomNavigatorState();
  }
}

class _bottomNavigatorState extends State<BottomNavigator>
    with TickerProviderStateMixin {
  late final AppLifecycleListener _listener;

  final _defaultColor = Colors.grey;
  final _activeColor = primary;
  late PageController _pageController;
  final _pages = <Widget>[
    const HomePage(),
    const RankingPage(),
    const FavoritePage(),
    const ProfilePage()
  ];

  var _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _listener = AppLifecycleListener(onResume: () {
      logger.i("onResume");
    }, onDetach: () {
      logger.i("onDetach");
    }, onHide: () {
      logger.i("onHide");
    }, onPause: () {
      logger.i("onPause");
    }, onInactive: () {
      logger.i("onInactive");
    }, onRestart: () {
      logger.i("onRestart");
    }, onShow: () {
      logger.i("onShow");
    }, onStateChange: (state) {
      logger.i("onStateChange: ${state.toString()}");
    });
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    _listener.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: _pageController,
        children: _pages,
        onPageChanged: (index) => _handlePageChanged(index),
      ),
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed,
          selectedItemColor: _activeColor,
          unselectedItemColor: _defaultColor,
          onTap: (index) {
            _jumpToTargetPage(index);
          },
          items: [
            _bottomItem("首页", Icons.home),
            _bottomItem("排行", Icons.local_fire_department),
            _bottomItem("收藏", Icons.favorite),
            _bottomItem("我的", Icons.live_tv)
          ]),
    );
  }

  void _jumpToTargetPage(int index) {
    setState(() {
      _currentIndex = index;
    });
    _pageController.jumpToPage(_currentIndex);
  }

  BottomNavigationBarItem _bottomItem(String label, IconData icon) {
    return BottomNavigationBarItem(
      label: label,
      icon: Icon(
        icon,
        color: _defaultColor,
      ),
      activeIcon: Icon(
        icon,
        color: _activeColor,
      ),
    );
  }

  void _handlePageChanged(int currentPageIndex) {
    setState(() {
      _currentIndex = currentPageIndex;
    });
  }
}
